package cn.liutao.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.liutao.common.exception.BadRequestException;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.Path;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author liutao
 * @Description 表单校验工具类
 * @date 2023/11/1 9:47
 * @Version 1.0
 */
@Slf4j
public class ValidUtil {

    private ValidUtil(){}
    private static volatile Validator validator;
    static {
        if (validator==null){
            synchronized (ValidUtil.class){
                if (validator==null){
                    validator = Validation.buildDefaultValidatorFactory().getValidator();

                }
            }
        }
    }

    public  static<T,U> void validated(T validObject,Class<U> group){
        Set<ConstraintViolation<T>> validates = validator.validate(validObject, group);
        StringBuffer sb = new StringBuffer();
        for (ConstraintViolation<T> validate : validates) {
            String message = validate.getMessage();
            Path property = validate.getPropertyPath();
            sb.append("属性【"+property+"】:校验失败，原因【"+message+"】");
        }
        String msg = sb.toString();
        if (StrUtil.isNotBlank(msg)){
            log.info(msg);
            throw new BadRequestException(msg);
        }

    }


}
